package com.moon.controller;

import com.moon.dao.TUserMapper;
import com.moon.entity.TUser;
import com.moon.service.VerificationCodeService;
import com.moon.utils.*;
import com.moon.vo.TUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@RequestMapping("/user")
//@CrossOrigin("*")
@RestController
public class UserController {

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    @Qualifier("idWorker1")
    IdWorker idWorker;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    TemplateEngine templateEngine;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("selectNicknameById")
    public String getNicknameById(Long id) {
        return tUserMapper.selectNicknameById(id);
    }
    @RequestMapping("/getemail")
    public String getemail(@RequestParam("sellerId") long sellerId){
        TUser user = new TUser();
        user.setId(sellerId);
        String email = tUserMapper.selectOne(user).getEmail();
        return email;
    }


    @RequestMapping("selectAllById")
    public Map<Object,Object> selectAllById(HttpServletRequest request, Long id){
        System.out.println("查询用户信息");
        String token = request.getHeader("token");
        TUser object = JwtUtils.getObject(token, TUser.class);
        System.out.println(object.getId());
        Map<Object,Object> map = new HashMap<>();
        TUser tUser = tUserMapper.selectByPrimaryKey(object.getId());
        tUser.setPassword("");
        map.put("user",tUser);
        System.out.println(tUserMapper.selectByPrimaryKey(object.getId()).getAccount());
        return map;
    }

    /**
     * 升级用户
     * @param tUserVo
     * @return String
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("update")
    @ResponseBody
    public String update(@RequestBody TUserVo tUserVo, HttpServletRequest request) throws NoSuchAlgorithmException {
        System.out.println("升级中");
        if ("".equals(tUserVo.getAccount()) || tUserVo.getAccount()==null){
            return "未填写账号名";
        }
        //判断用户是否存在
        TUser user = new TUser();
        user.setAccount(tUserVo.getAccount());
        if (tUserMapper.selectOne(user) == null){
            return "用户不存在";
        }
        //
        if ("".equals(tUserVo.getNickname()) || tUserVo.getNickname()==null){
            return "未填写name";
        }
        if ("".equals(tUserVo.getEmail()) || tUserVo.getEmail()==null){
            return "未填写email";
        }
        if (!EmailUtils.validate(tUserVo.getEmail())){
            return "邮箱格式不对";
        }
        if ("".equals(tUserVo.getTel()) || tUserVo.getTel()==null){
            return "未填写电话";
        }
        if (!TelUtils.validate(tUserVo.getTel())) {
            return "电话格式错误";
        }
        if ("".equals(tUserVo.getUserImg()) || tUserVo.getUserImg()==null){
            return "未上传图片";
        }
        //String hashedPassword = PasswordUtils.passwordEncrypt(tUserVo.getPassword());//密码加密

        TUser user0 = new TUser();
        user0.setAccount(tUserVo.getAccount());
        TUser tUser = tUserMapper.selectOne(user0);
        tUser.setNickname(tUserVo.getNickname());
        tUser.setEmail(tUserVo.getEmail());
        tUser.setTel(tUserVo.getTel());
        tUser.setUserImg(tUserVo.getUserImg());

        //
        //验证码验证
        // 从 session 中获取验证码
        //HttpSession session = request.getSession();
        //String emailVerificationCode = (String) session.getAttribute("email_verification_code");

        //
        //连接 Redis
        HashOperations ops = stringRedisTemplate.opsForHash();
        //从redis中取出验证码
        Object emailVerificationCode = ops.get("verifyCode", tUserVo.getEmail() + "");
        //

        // 获取用户输入的验证码
        //String verificationCode = request.getParameter("verification_code");

        // 进行验证。
        if (emailVerificationCode.equals(tUserVo.getVerifyCode())){
            System.out.println(tUserVo.toString());
            int insert = tUserMapper.updateByPrimaryKey(tUser);
            return "success";
        } else {
            return "验证码错误";
        }
        //

    }

    /**
     * 用户密码修改
     * @param tUserVo
     * @return String
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("updatePassword")
    @ResponseBody
    public String updatePassword(@RequestBody TUserVo tUserVo, HttpServletRequest request) throws NoSuchAlgorithmException {
        System.out.println("用户密码升级ing---");
        if ("".equals(tUserVo.getAccount()) || tUserVo.getAccount()==null){
            return "未填写账号名";
        }
        //判断用户是否存在
        TUser user = new TUser();
        user.setAccount(tUserVo.getAccount());
        if (tUserMapper.selectOne(user) == null){
            return "用户不存在";
        }
        //
        if ("".equals(tUserVo.getPassword()) || tUserVo.getPassword()==null){
            return "未填写密码";        }
        if ("".equals(tUserVo.getNickname()) || tUserVo.getNickname()==null){
            return "未填写name";
        }
        if ("".equals(tUserVo.getEmail()) || tUserVo.getEmail()==null){
            return "未填写email";
        }
        if (!EmailUtils.validate(tUserVo.getEmail())){
            return "邮箱格式不对";
        }
        if ("".equals(tUserVo.getTel()) || tUserVo.getTel()==null){
            return "未填写电话";
        }
        if (!TelUtils.validate(tUserVo.getTel())) {
            return "电话格式错误";
        }
        if ("".equals(tUserVo.getUserImg()) || tUserVo.getUserImg()==null){
            return "未上传图片";
        }
        String hashedPassword = PasswordUtils.passwordEncrypt(tUserVo.getPassword());//密码加密

        TUser user0 = new TUser();
        user0.setAccount(tUserVo.getAccount());
        TUser tUser = tUserMapper.selectOne(user0);
        tUser.setPassword(hashedPassword);

        //
        //验证码验证
        // 从 session 中获取验证码
        //HttpSession session = request.getSession();
        //String emailVerificationCode = (String) session.getAttribute("email_verification_code");

        //
        //连接 Redis
        HashOperations ops = stringRedisTemplate.opsForHash();
        //从redis中取出验证码
        Object emailVerificationCode = ops.get("verifyCode", tUserVo.getEmail() + "");
        //

        // 获取用户输入的验证码
        //String verificationCode = request.getParameter("verification_code");

        // 进行验证。
        if (emailVerificationCode.equals(tUserVo.getVerifyCode())){
            System.out.println(tUserVo.toString());
            int insert = tUserMapper.updateByPrimaryKey(tUser);
            return "success";
        } else {
            return "验证码错误";
        }
        //

    }

}
